﻿using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.AspNetCore.Http;
using WebSocketCore.Domain.Entities;
using WebSocketCore.Domain.Account;

namespace WebSocketCore.Domain.Impl
{
    public class WebSocketInvoker : IWebSocketInvoker
    {
        protected IChatRoomManager _chatRoomManager;
        protected IUserManager _userManager;
        protected IMessageManager _messageManager;
        protected static IList<WebSocketEntity> users = new List<WebSocketEntity>();
        public WebSocketInvoker(IChatRoomManager chatRoomManager, IUserManager userManager, IMessageManager messageManager)
        {
            this._chatRoomManager = chatRoomManager;
            this._userManager = userManager;
            this._messageManager = messageManager;
        }
        public async Task InvokeAsync(HttpContext context, WebSocket webSocket)
        {
            WsRequertCheck requestCheck = CheckRequest(context);
            if (requestCheck == WsRequertCheck.NotLoginIn)
            {
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "用户未登陆", CancellationToken.None);
                webSocket.Dispose();
                return;
            }
            if (requestCheck == WsRequertCheck.NotHaveRoomQuery)
            {
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "没有选择聊天室或聊天室Id不正确", CancellationToken.None);
                webSocket.Dispose();
                return;
            }
            IUser user = _userManager.GetUser(context.Session.Get<string>("User"));
            string roomId = context.Request.Query["room"];
            await _chatRoomManager.AddUserToRoom(roomId, user, webSocket);
        }

        private WsRequertCheck CheckRequest(HttpContext context)
        {
            if (!context.Session.Keys.Contains("User"))
            {
                return WsRequertCheck.NotLoginIn;
            }
            if (!context.Request.QueryString.HasValue || !_chatRoomManager.HasRoom(context.Request.Query["room"]))
            {
                return WsRequertCheck.NotHaveRoomQuery;
            }
            return WsRequertCheck.Success;
        }
        private enum WsRequertCheck
        {
            NotLoginIn,
            NotHaveRoomQuery,
            Success
        }
    }

}
